package com.tedu.springboot2211.controller;

import com.tedu.springboot2211.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 用于处理本网站中和用户相关的操作
 */
@Controller
public class UserController {
    //该File对象表示保存所有用户信息的目录:users
    private static File userDir;

    static {
        userDir = new File("./users");
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    //用于处理用户注册操作
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理用户注册！");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username + "," + password + "," + nickname + "," + ageStr);

        int age = Integer.parseInt(ageStr);
        User user = new User(username, password, nickname, age);
        //重载的File构造器，参数1:所在的父目录  参数2:该File对象表示的文件或目录
        File file = new File(userDir, username + ".obj");
        try (
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ) {
            //将该注册用户信息以User对象形式保存在文件中
            oos.writeObject(user);
            //将注册成功页面相应
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
